package com.define.commons.query.interceptor;

import com.define.commons.query.core.Query;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.util.Properties;

/*
 * @Author xiewenlong
 * @Date 2018/10/30 15:33
 * @Description 查询拦截器，分页
 */
@Component
@Intercepts(@Signature(type = Executor.class, method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
public class QueryInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        String sql = getSql(invocation);
        System.out.println(sql);
        //获取参数
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        //参数是Query类型的查询就处理分页
        if ((parameterObject instanceof Query)) {
            System.out.println("进入我的自定义拦截器。。。。。。");
            Query po = (Query) parameterObject;
            //获取sql
            //处理sql
            //sql = String.format("%s limit " + po.getOffset() + "," + po.getLimit(), sql);
            //重置sql
            //restSql2Invacation(invocation, sql);
            //执行sql
            //PageHelper.startPage(po.getPage(), po.getPageSize());
            Object result = invocation.proceed();
            //PageInfo<Map> pageInfo = new PageInfo<>((List) result);
            //包装结果
            return result;
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }

    /*
     * @Author xiewenlong
     * @Date 2018/10/30 17:19
     * @Description 把新的sql放到invocation中
     * @Param [invocation, sql]
     * @return void
     */
    public void restSql2Invacation(Invocation invocation, String sql) {
        final Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        BoundSql boundSql = ms.getBoundSql(parameterObject);

        MappedStatement newStatement = newMappedStatement(ms, new BoundSqlSqlSource(boundSql));
        MetaObject msObject = MetaObject.forObject(newStatement,
                new DefaultObjectFactory(),
                new DefaultObjectWrapperFactory(),
                new DefaultReflectorFactory());

        msObject.setValue("sqlSource.boundSql.sql", sql);
        args[0] = newStatement;
    }

    /*
     * @Author xiewenlong
     * @Date 2018/10/30 16:41
     * @Description 根据MappedStatement和SqlSource生成新的MappedStatement
     * @Param [ms, newSqlSource]
     * @return org.apache.ibatis.mapping.MappedStatement
     */
    private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder =
                new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
            StringBuilder keyProperties = new StringBuilder();
            for (String keyProperty : ms.getKeyProperties()) {
                keyProperties.append(keyProperty).append(",");
            }
            keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
            builder.keyProperty(keyProperties.toString());
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());

        return builder.build();
    }

    /*
     * @Author xiewenlong
     * @Date 2018/10/30 15:48
     * @Description 根据invocation获取sql
     * @Param [invocation]
     * @return java.lang.String
     */
    public String getSql(Invocation invocation) {
        final Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        return ms.getBoundSql(parameterObject).getSql();
    }

    //定义一个内部辅助类，作用是包装sq
    class BoundSqlSqlSource implements SqlSource {
        private BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        @Override
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }
}